package com.pansoft.openplanet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.efounder.chat.model.LogoutEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.FileDeleteUtil;
import com.efounder.util.ToastUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.manager.OpenPlanetLoginManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.RegexUtils;
import com.utilcode.util.StringUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 重置密码（手机验证码或者邮箱验证码重置）
 * Created by yqs on 2018/06/05
 *
 * @author yqs
 */

public class ResetPasswordActivity extends TCBaseActivity implements View.OnClickListener
        , OpenPlanetLoginManager.LoginListener {
    public static final String TAG = "ResetPasswordActivity";

    private TextView tvNumber;
    private EditText etNumber;
    private View viewDivider1;
    private TextView tvGetCode;
    private EditText etPwd;
    private EditText etEnterPwd;
    private Button buttonResetPwd;
    private String number;
    private TimeCount timeCount;
    private OpenPlanetLoginManager loginManager;
    private boolean needLogOut = false;
    //1是手机号  2是邮箱
    private int loginType = 1;

    /**
     * @param context
     * @param number     手机号
     * @param needLogOut 是否需要注销用户
     */
    public static void start(Context context, String number, boolean needLogOut) {
        Intent starter = new Intent(context, ResetPasswordActivity.class);
        starter.putExtra("number", number);
        starter.putExtra("needLogOut", needLogOut);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_reset_password);
        initView();
        initData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
        timeCount.cancel();
    }


    private void initView() {
        tvNumber = (TextView) findViewById(R.id.tv_number);
        etNumber = (EditText) findViewById(R.id.et_number);
        viewDivider1 = (View) findViewById(R.id.view_divider1);
        tvGetCode = (TextView) findViewById(R.id.tv_get_code);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        etEnterPwd = (EditText) findViewById(R.id.et_enter_pwd);
        buttonResetPwd = (Button) findViewById(R.id.button_reset_pwd);

        tvGetCode.setOnClickListener(this);
        buttonResetPwd.setOnClickListener(this);

    }

    private void initData() {
        number = getIntent().getStringExtra("number");
        needLogOut = getIntent().getBooleanExtra("needLogOut", false);
        timeCount = new TimeCount(60000, 1000);//构造CountDownTimer对象
        tvNumber.setText(number);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.open_planet_reset_pw);
        loginManager = new OpenPlanetLoginManager(this);
        loginManager.setLoginListener(this);
        loginManager.setCheckApkVersion(false);

        if (RegexUtils.isEmail(number)) {
            // 如果是邮箱
            etNumber.setHint(R.string.openplanet_input_email_code);
            loginType = 2;
        } else {
            loginType = 1;
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_get_code) {
            getVerifyCode();
        } else if (id == R.id.button_reset_pwd) {
            resetPwdToServer();
        }
    }

    private void resetPwdToServer() {
        String pwd = etPwd.getText().toString().trim();
        String enterPwd = etEnterPwd.getText().toString().trim();
        String verificode = etNumber.getText().toString().trim();
        ToastUtils.setGravity(Gravity.CENTER, 0, 0);
        if (TextUtils.isEmpty(verificode)) {
            ToastUtils.showShort(getResources().getString(R.string.login_reset_password_sms_code_not_empty));
            return;
        }
        if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(pwd)) {
            ToastUtils.showShort(getResources().getString(R.string.login_reset_password_password_not_empty));
            return;
        }
        if (pwd.length() < 8) {
            ToastUtils.showShort(getResources().getString(R.string.open_planet_password_number));
            return;
        }
        if (!TextUtils.equals(pwd, enterPwd)) {
            ToastUtils.showShort(getResources().getString(R.string.login_reset_password_password_not_same));
            return;
        }

        //1.使用短信验证码登录 获取 accesstoken  然后重置密码
        if (loginType == 1) {
            loginManager.login(number, verificode, "smsCode");
        } else {
            //邮箱验证码登录 获取 accesstoken  然后重置密码
            resetEmailPassword();
        }

    }

    private void getVerifyCode() {
        showLoading(R.string.common_text_please_wait);
        etNumber.setFocusable(true);
        etNumber.setFocusableInTouchMode(true);
        etNumber.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(1, InputMethodManager.HIDE_NOT_ALWAYS);
        requestCode();
    }

    /**
     * 请求验证码
     */
    private void requestCode() {
        String url;
        HashMap<String, String> params = new HashMap<>();
        if (loginType == 1) {
            url = "user/sendVerifyCode2mobilePhone";
            params.put("phoneNumber", number);
            TCRequestUtil.getCommonRequest(TAG, url, params, new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    dismissLoading();
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getString("result").equals("success")) {
                            timeCount.start();
                            ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_success));
                        } else {
                            ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_fails));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_fails));
                    }
                }

                @Override
                public void onFail(String error) {
                    dismissLoading();
                    ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_fails));
                }
            });
        } else {
            url = "email/emailPasswordRetrieval";
            params.put("userId", number);
            TCRequestUtil.postCommonRequest(TAG, url, params, new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    dismissLoading();
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getString("result").equals("success")) {
                            timeCount.start();
                            ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_success));
                        } else {
                            ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_fails));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_fails));
                    }
                }

                @Override
                public void onFail(String error) {
                    dismissLoading();
                    ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_send_sms_code_fails));
                }
            });
        }
    }

    /**
     * 修改邮箱登录的密码
     */
    private void resetEmailPassword() {
        showLoading(R.string.common_text_please_wait);
        String url;
        HashMap<String, String> params = new HashMap<>();
        url = "email/checkResetLink";
        params.put("userId", number);
        params.put("newPwd", etPwd.getText().toString().trim());
        params.put("sid", etNumber.getText().toString().trim());
        TCRequestUtil.postCommonRequest(TAG, url, params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("result").equals("success")) {
                        ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_reset_success));
                        finish();
                    } else {
                        String msg = jsonObject.optString("msg");
                        if (!StringUtils.isEmpty(msg)) {
                            ToastUtil.showToast(getApplicationContext(), msg);
                            return;
                        }
                        ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_reset_fails));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_reset_fails));
                }
            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), getResources().getString(R.string.login_reset_password_reset_fails));
            }
        });
    }

    @Override
    public void tcLoginSuccess() {
        //不是真正的想让用户登录，所以参数保存为空
        EnvironmentVariable.setProperty("tc_ethAddress", "");
        //todo 兼容ios
        EnvironmentVariable.setProperty("tc_ethPublicKey", "");
        EnvironmentVariable.setProperty("tc_planet", "");
        //保存用户 rsa 工钥
        EnvironmentVariable.setUserID("");
        EnvironmentVariable.setProperty(CHAT_PASSWORD, "");
        EnvironmentVariable.setUserName("");
        EnvironmentVariable.setPassword("");

        String accessToken = EnvironmentVariable.getProperty("tc_access_token", "");

        //使用accesstoken重置密码
        HashMap<String, String> params = new HashMap<>();
        params.put("newPassword", etEnterPwd.getText().toString());
        params.put("access_token", accessToken);
        TCRequestUtil.getCommonRequest(TAG, "user/resetPassword", params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {


                dismissLoading();


                //删除keystore 和数据库
                File dirFile = new File(TalkChainConstant
                        .getDataFilePath(ResetPasswordActivity.this) + File.separator + number);
                FileDeleteUtil.delete(dirFile);
                //从数据库中移除
                //new AccountDao(ResetPasswordActivity.this).deleteAllAccount();

                new AccountDao(ResetPasswordActivity.this).deleteByCurentImuserId();
                EnvironmentVariable.setProperty(CHAT_USER_ID, "");
                if (needLogOut) {
                    showLoginDialog();
                } else {
                    ToastUtil.showToast(ResetPasswordActivity.this, getResources().getString(R.string.login_reset_password_reset_success));
                    finishAffinity();
                }


            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                EnvironmentVariable.setProperty(CHAT_USER_ID, "");
                ToastUtil.showToast(ResetPasswordActivity.this, getResources().getString(R.string.login_reset_password_reset_fails));
            }
        });
    }

    private void showLoginDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setMessage(getResources().getString(R.string.login_reset_password_reset_success_login))
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        EventBus.getDefault().post(new LogoutEvent());
                        finishAffinity();
                    }
                }).setCancelable(false)
                .create().show();

    }

    @Override
    public void showLoginLoading(String msg) {
        showLoading(getResources().getString(R.string.talk_chain_loding_wait));
    }

    @Override
    public void dismissLoginloading() {
        // dismissLoading();
    }

    @Override
    public void tcLoginFail(String error) {
        dismissLoading();
        ToastUtil.showToast(this, getResources().getString(R.string.login_reset_password_reset_fails_code_error));
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            tvGetCode.setText(getResources().getString(R.string.login_reset_password_again_send));
            tvGetCode.setClickable(true);
            tvGetCode.setTextColor(getResources().getColor(R.color.tc_orange_color));

        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            if (isFinishing()) {
                return;
            }

            tvGetCode.setClickable(false);
            tvGetCode.setText(getResources().getString(R.string.login_reset_password_again_send)
                    + "(" + millisUntilFinished / 1000 + getResources().getString(R.string.login_reset_password_second) + ")");
            tvGetCode.setTextColor(getResources().getColor(R.color.edit_hint_text_color));
        }
    }

}